<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible && !detailInfo.visible && !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clearType="clearType"
          :slipSelectRequest="slipSelectRequest"
        >
        </NewPageFilter>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-submit>
            <el-button :disabled="!canSubmit" @click="submit()">提交</el-button>
          </template>
          <template v-slot:filter-downloadTemplate>
            <el-button @click="downloadTemplate()">下载模板</el-button>
          </template>
          <template v-slot:filter-uploadCapitalProject>
            <el-upload
              :headers="uploadInfo.headers"
              :show-file-list="false"
              :on-error="uploadError"
              :on-success="importProduct"
              :before-upload="beforeProductUpload"
              :action="uploadInfo.action"
            >
              <el-button>导入模板</el-button>
            </el-upload>
          </template>
          <template v-slot:filter-excel>
            <el-button @click="exportExcel()">导出excel</el-button>
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-code="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.code
          }}</span>
        </template>
      </table-container>
    </div>

    <modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :id="modifyInfo.id"
      :type="modifyInfo.type"
      @returnBack="returnModify"
    />

    <detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :table-row="detailInfo.data"
      @returnBack="getList"
    />
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:formData="advancedSearchInfo.data"
      :fieldList="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <!-- <DetailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></DetailList> -->
    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio label="page">当前页数据</el-radio>
          <el-radio label="all">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
    <chose-printer :visible="printerInfo.visible" @callBack="printerCallBack" />
  </div>
</template>

<script setup name="capitalProject">
import NewPageFilter from '@/components/NewPageFilter/index'
import TableContainer from '@/components/TableContainer/index'
import {
  getCapitalProjectCustomizeListPage,
  deleteCapitalProject,
  submitCapitalProject,
  revokeCapitalProject,
  printForListAssetUseExportOrders,
  excelForListCapitalProject,
} from '@/api/asset.js'
import modify from './modify'
import detail from './detail'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { getDepotAll } from '@/api/core'
import PageDialog from '@/components/PageDialog/index'
import { fatchTemplateByCode } from '@/api/base'
import { exportTemplateExcel } from '@/api/pub'
import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'

const { proxy } = getCurrentInstance()

const uploadInfo = reactive({
  action:
    axios.defaults.baseURL + '/asset/settings/capitalProject/import/excel',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})
// 过滤相关配置
const filterInfo = reactive({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('capitalProject:add'),
    },
    {
      type: 'slot',
      value: 'submit',
      show: proxy.$permission('capitalProject:submit'),
    },
    {
      type: 'slot',
      value: 'downloadTemplate',
      show: proxy.$permission('capitalProject:downloadTemplate'),
    },
    {
      type: 'slot',
      value: 'uploadCapitalProject',
      show: proxy.$permission('capitalProject:uploadCapitalProject'),
    },
    {
      type: 'slot',
      value: 'excel',
      show: proxy.$permission('capitalProject:excelList'),
    },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      // 待提交1  完成 2
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('capitalProject:submit'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '修改',
        event: update,
        show: proxy.$permission('capitalProject:update'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
      {
        label: '撤回',
        event: revoke,
        show: proxy.$permission('capitalProject:revoke'),
        ifRender: function (row) {
          return row.status === 2
        },
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('capitalProject:delete'),
        ifRender: function (row) {
          return row.status === 1
        },
      },
    ],
  },
})
const modifyInfo = reactive({
  visible: false,
  id: '',
  title: '',
  type: '',
})
const detailListInfo = reactive({
  visible: false,
})
const detailInfo = reactive({
  visible: false,
  data: {},
})
const preferenceInfo = reactive({
  visible: false,
})
const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})

const printerInfo = reactive({
  visible: false,
  data: {},
})
const dialogInfo = reactive({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: 'page',
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
let page = reactive({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const clearType = ref(true)
const slipSelectRequest = ref(true)

const canSubmit = computed(() => {
  return (
    tableInfo.selections.length &&
    tableInfo.selections.filter((item) => item.status === 1).length
  )
})

let obj = {
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'asset_capital_project_status',
    show: false,
    hidden: true,
  },
  code: {
    label: '编码',
    value: 'code',
    componentType: 'input',
    type: 'slot',
    show: false,
    hidden: true,
  },
  name: {
    label: '名称',
    value: 'name',
    componentType: 'input',
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()

function uploadError(err) {
  if (err) {
    ElMessage.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.loading.close()
}
function beforeProductUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.loading.close()
    return false
  }
  return isFileType && isLt
}
function importProduct(resp) {
  uploadInfo.loading.close()
  if (resp && resp.success) {
    ElMessage.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    getList()
  } else {
    ElMessage.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    })
  }
}
function pageInfo(obj) {
  page = obj
}
function printerCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.data, printer)
  }
  printerInfo.visible = false
}
function handleClose() {
  dialogInfo.visible = false
}
function handlePrinterCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.data, printer)
  }
  printerInfo.visible = false
}
function checkConfirm() {
  if (dialogInfo.type === 'excel') {
    exportExcelList()
  } else if (dialogInfo.type === 'print') {
    printList()
  }
  dialogInfo.visible = false
  dialogInfo.msg = ''
}
function downloadTemplate() {
  exportTemplateExcel('capital_project_import').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function uploadCapitalProject() {}
function exportExcel() {
  dialogInfo.visible = true
  dialogInfo.type = 'excel'
  dialogInfo.msg = '请选择数据导出范围'
  dialogInfo.btList[1].label = '导出'
  dialogInfo.flag = 'page'
}
function exportExcelList() {
  if (dialogInfo.flag === 'select') {
    if (!tableInfo.selections.length) {
      ElMessage.warning({
        message: '请选择数据！',
        showClose: true,
        duration: 3000,
      })
      return
    }
  }
  let params = {
    ...filterInfo.query,
    ...page,
    page: dialogInfo.flag === 'page' ? true : false,
  }

  excelForListCapitalProject(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}

async function print() {
  dialogInfo.visible = true
  dialogInfo.type = 'print'
  dialogInfo.msg = '请选择当数据打印范围'
  dialogInfo.btList[1].label = '打印'
  dialogInfo.flag = 'page'
}

function printList() {
  fatchTemplateByCode({
    resourceCode: 'capitalProject:printList',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, dialogInfo.flag)
    }
  })
}
function getPrintData(temp, flag) {
  if (dialogInfo.flag === 'select') {
    if (!tableInfo.selections.length) {
      ElMessage.warning({
        message: '请选择数据！',
        showClose: true,
        duration: 3000,
      })
      return
    }
  }
  let query = {
    customizeDto: filterInfo.query,
  }
  let params = {
    ...query,
    ...page,
    page: flag === 'page' ? true : false,
  }
  printForListAssetUseExportOrders(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function returnModify() {
  if (modifyInfo.id) {
    getList()
  } else {
    search()
  }
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.query.queryMap = {}
  filterInfo.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
}
// 获取列表
async function getList() {
  tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页

  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
//删除
function remove(row) {
  const data = []
  data.push(row.id)
  deleteCapitalProject(data).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//创建
function create() {
  modifyInfo.id = ''
  modifyInfo.type = 'create'
  modifyInfo.title = '新增资金项目'
  modifyInfo.visible = true
}
function update(row) {
  sessionStorage.setItem('storeRowId', row.id)
  modifyInfo.id = row.id
  modifyInfo.type = 'update'
  modifyInfo.title = '修改资金项目'
  modifyInfo.visible = true
}
//提交
function submit(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.selections.map((item) => item.id)
  }
  submitCapitalProject(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function revoke(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.selections.map((item) => item.id)
  }
  revokeCapitalProject(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}

//展示明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.data = row
  detailInfo.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.data = {}
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'AssetCapitalProjectList-com.slip.spd.entity.vo.asset.settings.AssetCapitalProjectVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.query.queryMap,
      }
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.api = getCapitalProjectCustomizeListPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.sortArr)
    filterInfo.sortArr = arr
    filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped></style>
